package com.xw.bo.ks.config;

import com.xw.bo.ks.client.WechatClient;
import com.xw.bo.ks.controller.BaseController;
import com.xw.bo.ks.entity.base.HeadData;
import com.xw.bo.ks.entity.base.JsonResult;
import com.xw.bo.ks.entity.exception.BaseException;
import com.xw.bo.ks.entity.exception.IException;
import com.xw.bo.ks.util.DateUtils;
import com.xw.bo.ks.util.WechatClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @Value("${ks.token.refresh:0}")
    private Integer refresh;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity defaultErrorHandler(HttpServletRequest req, HttpServletResponse res, Exception ex) throws Exception {
        JsonResult errResult = null;
        try {
            //存在业务异常
            if (ex instanceof BaseException) {
                IException iException = ((BaseException) ex).getiException();
                /**
                 * 存在业务异常枚举  输出到前端 记录日志
                 */
                if (iException != null) {
                    int httpCode = 555;

                    errResult = new JsonResult(iException.getErrCode(), iException.getErrMessage());
                    if (ex.getCause() != null) {
                        log.error("exceptionMessage:", ex);
                    }
                }

                String message = getExceptionMessage(iException.getErrCode(), iException.getErrMessage(), req.getRequestURI());


            } else {
                errResult = new JsonResult(556, "操作异常");
                log.error("exceptionMessage:", ex);

                String message = getExceptionMessage(556, "系统异常，" + ex.getMessage(), req.getRequestURI());

            }

        } catch (Exception e) {
            errResult = new JsonResult(555, "操作异常");
            log.error("全局异常处理失败:", e);
        }
        errResult.setRequest_id(getRequestId());

        BaseController.dsAuth.remove();
        BaseController.JSESSIONID.remove();
        BaseController.headDataLocal.remove();
        BaseController.token.remove();
        return ResponseEntity.ok(errResult);
    }

    private String getExceptionMessage(Integer code, String message, String uri) {

        StringBuilder stringBuffer = new StringBuilder();
        stringBuffer.append("全局异常捕捉消息：");
        stringBuffer.append(" 当前时间:");
        stringBuffer.append(DateUtils.formatDateByNumber(System.currentTimeMillis(), DateUtils.DATE_PATTERN_DEFAULT));
        stringBuffer.append(", 异常码:");
        stringBuffer.append(code);
        stringBuffer.append(", 异常原因:");
        stringBuffer.append(message);
        stringBuffer.append(", 请求接口:");
        stringBuffer.append(uri);

        return stringBuffer.toString();
    }

    public String getRequestId() {

        HeadData headData = BaseController.headDataLocal.get();
        if (null == headData){
            return "";
        }
        String requestId = headData.getRequestId();
        if (StringUtils.isEmpty(requestId)) {
            log.error("请求头中的request_id为空}");
        }
        return requestId;
    }

}
